<template>
  <el-upload
    ref="elupload"
    class="avatar-uploader"
    action="#"
    :http-request="httpRequest"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
export default {
  methods: {
    http_request (val) {
      console.log(val)
    },
    beforeAvatarUpload (file) {
      console.log(file)
      this.imgName = file.name
      this.nowFile = file
    },
    httpRequest (data) {
      this.imageUrl = URL.createObjectURL(data.file)
      //这是限制上传文件类型 
      const isPFX = data.file.type === 'image/jpeg' || data.file.type === 'image/jpg' || data.file.type === 'image/png'
      const isLt2M = data.file.size / 1024 / 1024 < 2
      if (!isPFX) {
        this.$message.error("上传头像图片只能是 JPG、PNG、JPEG 格式!")
      } else if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!")
      } else {
        this.getBase64(data.file).then(resBase64 => {
          this.fileBase64 = resBase64.split(',')[1]　　//直接拿到base64信息
          this.tempUrl = resBase64.split(',')[1]
        })
      }
    },
    //这个file参数 也就是文件信息，你使用 插件 时 你就可以打印出文件信息 看看嘛
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader()
        let fileResult = ""
        reader.readAsDataURL(file)
        //开始转
        reader.onload = function () {
          fileResult = reader.result
        }
        //转 失败
        reader.onerror = function (error) {
          reject(error)
        }
        //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult)
        }
      })
    },

  },
}
</script>

<style>
</style>